import { useRef } from 'react'
import { useAppSelector, useAppDispatch } from '../../hooks'

import { RootState } from '../../store'
import {
  incrementActions,
  decrementActions,
  asyncIncrementActions
} from '../../store/reducers/count'

function Count() {
  const ref = useRef<HTMLSelectElement | null>(null)
  const { count } = useAppSelector((state: RootState) => state.count)
  const { users } = useAppSelector((state: RootState) => state.persons)
  const dispatch = useAppDispatch()

  // 加法
  const increment = () => {
    const { value } = ref.current!
    dispatch(incrementActions(Number(value)))
  }

  // 减法
  const decrement = () => {
    const { value } = ref.current!
    dispatch(decrementActions(Number(value)))
  }

  // 奇数再加
  const incrementIfOdd = () => {
    const { value } = ref.current!
		if(count % 2 !== 0){
      dispatch(incrementActions(Number(value)))
		}
  }

  // 异步加
  const incrementAsync = () => {
    const { value } = ref.current!
    dispatch(asyncIncrementActions(Number(value), 500))
  }

  return (
    <div>
      <h2>我是Count组件,下方组件总人数为:{users.length}</h2>
      <h3>和为：{count}</h3>
      <select ref={ref}>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>&nbsp;
      <button onClick={increment}>+</button>&nbsp;
      <button onClick={decrement}>-</button>&nbsp;
      <button onClick={incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
      <button onClick={incrementAsync}>异步加</button>&nbsp;
    </div>
  )
}

export default Count
